<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryFormRef"
      size="small"
      :inline="true"
      v-show="showSearch"
    >
      <el-form-item label="用户名称" prop="userName">
        <el-input
          v-model="queryParams.userName"
          placeholder="请输入用户名称"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="手机号码" prop="phonenumber">
        <el-input
          v-model="queryParams.phonenumber"
          placeholder="请输入手机号码"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          size="small"
          @click="openSelectUser"
          v-hasPermi="['system:role:add']"
          >添加用户</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="CircleClose"
          size="small"
          :disabled="multiple"
          @click="cancelAuthUserAll"
          v-hasPermi="['system:role:remove']"
          >批量取消授权</el-button
        >
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="Close" size="small" @click="handleClose"
          >关闭</el-button
        >
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="userList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="用户名称" prop="userName" :show-overflow-tooltip="true" />
      <el-table-column label="用户昵称" prop="nickName" :show-overflow-tooltip="true" />
      <el-table-column label="邮箱" prop="email" :show-overflow-tooltip="true" />
      <el-table-column label="手机" prop="phonenumber" :show-overflow-tooltip="true" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="dict.sys_normal_disable" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180">
        <template #default="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            size="small"
            type="text"
            icon="CircleClose"
            @click="cancelAuthUser(scope.row)"
            v-hasPermi="['system:role:remove']"
            >取消授权</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <SelectUser ref="selectRef" :role-id="queryParams.roleId" @ok="handleQuery" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, getCurrentInstance } from 'vue'
import { useRouter } from 'vue-router'
import { allocatedUserList, authUserCancel, authUserCancelAll } from '@/api/system/role'
import SelectUser from './selectUser.vue'
import { ElForm, ElTable, ElMessage, ElMessageBox } from 'element-plus'
import { useDict } from '@/utils/dict'
import { parseTime } from '@/utils/cj'

defineOptions({
  name: 'AuthUser',
})

const { dict }: any = useDict({
  dicts: ['sys_normal_disable'],
})

const { proxy } = getCurrentInstance() as any
const router = useRouter()

const queryFormRef = ref<InstanceType<typeof ElForm>>()
const selectRef = ref()

const loading = ref(true)
const userIds = ref<string[]>([])
const multiple = ref(true)
const showSearch = ref(true)
const total = ref(0)
const userList = ref([])

const queryParams = reactive<Record<string, any>>({
  pageNum: 1,
  pageSize: 10,
  roleId: undefined,
  userName: undefined,
  phonenumber: undefined,
})

onMounted(() => {
  const roleId = router.currentRoute.value.params && router.currentRoute.value.params.roleId
  if (roleId) {
    queryParams.roleId = roleId
    getList()
  }
})

/** 查询授权用户列表 */
const getList = () => {
  loading.value = true
  allocatedUserList(queryParams).then((response: any) => {
    userList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}

// 返回按钮
const handleClose = () => {
  proxy.$tab.closeOpenPage({ path: '/system/role' })
}

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.pageNum = 1
  getList()
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  handleQuery()
}

// 多选框选中数据
const handleSelectionChange = (selection: any[]) => {
  userIds.value = selection.map((item) => item.userId)
  multiple.value = !selection.length
}

/** 打开授权用户表弹窗 */
const openSelectUser = () => {
  selectRef.value.show()
}

/** 取消授权按钮操作 */
const cancelAuthUser = (row: any) => {
  const roleId = queryParams.roleId
  ElMessageBox.confirm('确认要取消该用户"' + row.userName + '"角色吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => authUserCancel({ userId: row.userId, roleId: roleId }))
    .then(() => {
      getList()
      ElMessage.success('取消授权成功')
    })
    .catch(() => {})
}

/** 批量取消授权按钮操作 */
const cancelAuthUserAll = (row: any) => {
  const roleId = queryParams.roleId
  const userIdsStr = userIds.value.join(',')
  ElMessageBox.confirm('是否取消选中用户授权数据项？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => authUserCancelAll({ roleId: roleId, userIds: userIdsStr }))
    .then(() => {
      getList()
      ElMessage.success('取消授权成功')
    })
    .catch(() => {})
}
</script>
